package org.fuxia.im.common;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.fuxia.im.core.AbstractContext;
import org.fuxia.im.core.socket.impl.ECNioClient;
import org.fuxia.im.entities.User;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 客户端上下文信息
 */
@SuppressWarnings("unchecked")
public class ClientContext extends AbstractContext {
	private static final String CONFIG_FILE_PATH = "configs/client-config.properties";
	private static ClientContext instance;
	private static byte[] lock = new byte[1];
	private Properties configProps;

	private void initContext() {
		Iterator<Object> keyIter = configProps.keySet().iterator();
		while (keyIter.hasNext()) {
			String key = keyIter.next().toString();
			this.put(key, configProps.get(key));
		}
		Object rootDir = this.get("root-dir") ;
		if(rootDir==null) {
			rootDir = "c:\\IMUser" ;
		}
		File dir= new File(rootDir.toString());
		if(!dir.exists()) {
			dir.mkdir() ;
		}
		
		
	}


	private ClientContext() {
		context = new ConcurrentHashMap<Object, Object>();
		configProps = new Properties();
		try {
			configProps.load(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream(CONFIG_FILE_PATH));
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
		initContext();
	}

	public static ClientContext getContext() {
		synchronized (lock) {
			if (instance == null) {
				instance = new ClientContext();
			}
		}
		return instance;
	}

	public void setClient(ECNioClient client) {
		this.put(ClientConst.CLIENT, client);
	}

	/**
	 * 获取连接客户端
	 * @return
	 */
	public ECNioClient getClient() {
		return this.get(ClientConst.CLIENT, ECNioClient.class);
	}

	public static void putValue(Object key, Object value) {
		instance.put(key, value);
	}

	public static Object getValue(Object key) {
		return instance.get(key);
	}

	public static <T> T getValue(Object key, Class<T> clazz) {
		return instance.get(key, clazz);
	}

	public static Object removeKey(Object key) {
		return instance.remove(key);
	}

	/**
	 * 获取登陆用户
	 * @return
	 */
	public static User getLoginUser() {
		return getValue(ClientConst.CURRENT_USER, User.class);
	}

	
	/**
	 * 根据用户账户查找用户信息
	 * @param userCode
	 * @return
	 */
	public static User findUserByCode(String userCode) {
		Map<String, List<JSONArray>> users = ClientContext.getValue(
				ClientConst.FRIENDS, Map.class);
		if (users != null && users.size() > 0) {
			for (Iterator<Map.Entry<String, List<JSONArray>>> iter = users
					.entrySet().iterator(); iter.hasNext();) {
				List<JSONArray> obj = iter.next().getValue();
				if (obj != null) {
					for (JSONArray cur : obj) {
						if (cur.getString(0).equals(userCode)) {
							User user = new User();
							user.setUserCode(cur.getString(0));
							user.setNickName(cur.getString(1));
							user.setPersonNote(cur.getString(2));
							user.setUserState(cur.getShort(3));
							user.setImagePath(cur.getString(4));
							user.setAge(cur.getInteger(5));
							user.setAddress(cur.getString(6));
							user.setSex(cur.getString(7));
							return user;
						}
					}
				}
			}
		}

		return null;
	}

	/**
	 * @param groupkey  groupid#grouname
	 * @param users
	 */
	public static void addUserToGroup(String groupkey,JSONArray users) {
		Map<String, List<JSONArray>> map =ClientContext.getValue(ClientConst.FRIENDS,Map.class) ;
		List<JSONArray> uses = map.get(groupkey);
		if(uses!=null) {
			uses.add(users);
			ClientContext.getValue(ClientConst.FRIENDS,Map.class).remove(groupkey);
			ClientContext.getValue(ClientConst.FRIENDS,Map.class).put(groupkey, uses);
		}
	}
	
	/**
	 * 根据聊天群组ID删除上下文中的聊天群信息
	 * @param id
	 */
	public static void removeChatGroupById(String id) {
		List<JSONObject> obj = ClientContext.getValue(ClientConst.GROUPS, List.class);
		for(Iterator<JSONObject> iter = obj.iterator();iter.hasNext();) {
			if(iter.next().getString("id").equals(id)) {
				iter.remove();
				return ;
			}
		}
	}
	
	/**
	 * 查找聊天群组中的好友
	 * @param id
	 * @return
	 */
	public static JSONObject findChatGroupById(String id) {
		List<JSONObject> obj = ClientContext.getValue(ClientConst.GROUPS, List.class);
		for(Iterator<JSONObject> iter = obj.iterator();iter.hasNext();) {
			JSONObject data = iter.next() ;
			if(data.getString("id").equals(id)) {
				return data;
			}
		}
		return null ;
	}
	
	/**
	 * 删除用户拥有的好友分组中的用户
	 * @param userGroupKey
	 * @param userId
	 */
	public static void delUserInGroup(String userGroupKey,String userId) {
		Map<String,List<JSONArray>> users = ClientContext.getValue(ClientConst.FRIENDS, Map.class) ;
		if(users!=null) {
			List<JSONArray> user = users.get(userGroupKey) ;
			Iterator<JSONArray> usersIter = user.iterator() ;
			while(usersIter.hasNext()) {
				JSONArray cur = usersIter.next() ;
				if(cur.getString(0).equals(userId)) {
					usersIter.remove() ;
					break;
				}
			}
			
		}
	}
	
	/**
	 * 删除聊天群里面的好友
	 * @param userCode
	 * @param groupId
	 */
	public static void removeUserInGroup(String userCode,String groupId) {
		JSONObject obj = findChatGroupById(groupId);
		JSONArray users = (JSONArray) obj.get("users") ;
		for(int i=0;i<users.size();i++) {
			JSONArray data = (JSONArray)users.get(i);
			if(data.getString(0).equals(userCode)) {
				users.remove(i);
				break;
			}
		}
	}
	
	public static void addUserInChatGroup(String groupId,String userCode,String nickName) {
		JSONObject obj = findChatGroupById(groupId);
		JSONArray users = (JSONArray) obj.get("users") ;
		JSONArray newUser = new JSONArray(); 
		newUser.add(0, userCode);
		newUser.add(1,nickName);
		users.add(newUser);
	}
}
